// axios.get post
// wx.reqquest ->promise
// request(options) get/post ->put delete
// errorHandle
// abort

import config from '../pages/commponents/config'
import { Storetoken } from './wxstore'
console.log('intest', process.env.NODE_ENV)
const baseurl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro
const pending = {}
const isHttpSuccess = (status) => {
  return status >= 200 && status < 300
}
const errorHandle = (res) => {
  console.log(res)
  wx.showToast({
    title: res.data && res.data.msg ? res.data.msg : '请求异常',
    icon: 'none',
    duration: 2000
  })
}
export const request = async (options = {}) => {
  const { success, fail } = options
  const key = options.url + '&' + (options.method || 'GET')
  let isPublic = false
  config.publicPath.map((path) => {
    isPublic = isPublic || path.test(options.url)
  })
  // await Storetoken.set('111122')
  const token = await Storetoken.get()
  let header = {}
  if (!isPublic && token) {
    console.log('token', token)
    header = Object.assign({
      'Authorization': 'Bearer ' + token
    }, options.header)
  }
  options.url = baseurl + options.url
  const result = new Promise((resolve, reject) => {
    wx.showLoading()
    const handler = wx.request(
      Object.assign({}, options, {
        header,
        success: (res) => {
          delete pending[key]
          if (isHttpSuccess(res.statusCode)) {
            if (success) {
              success(res.data)
              return
            }
            resolve(res.data)
          } else {
            errorHandle(res)
            reject(res)
          }
        },
        fail: (err) => {
          delete pending[key]
          if (fail) {
            fail(err)
            return
          }
          reject(err)
        },
        complete: () => {
          wx.hideLoading()
        }
      }
      ))
    if (pending[key]) {
      pending[key].abort()
    }
    setTimeout(() => {
      pending[key] = handler
    }, 0)
  })
  return result
}

export const axios = {
  get (url, data, options = {}) {
    return request({
      url,
      data,
      method: 'GET',
      ...options
    })
  },
  post (url, data, options = {}) {
    return request({
      url,
      data,
      method: 'POST',
      ...options
    })
  }
}
